package com.ysq.www.common.utils.h5;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ysq.www.api.user.entity.WxConfig;
import com.ysq.www.api.user.service.IWxConfigService;
import com.ysq.www.common.config.ApplicationContextUtil;
import com.ysq.www.common.utils.client.ClientUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author dql
 * @Description H5工具类
 * @Date 2020/9/16 0016
 */
@Component
public class H5Utils {

    private static Logger logger = LoggerFactory.getLogger(H5Utils.class);

    /**
     * 静默授权登录
     * @param code 验证码
     * @param asId 协会id
     * @return Map
     */
    public static Map<String,String> getOpenId(String code,Integer asId){
        Map<String,String> resMap = new HashMap<>();
        IWxConfigService wxConfigService = ApplicationContextUtil.get(IWxConfigService.class);
        QueryWrapper<WxConfig> wrapper = new QueryWrapper<>();
        wrapper.eq("status",0).eq("as_id",asId);
        WxConfig wc = wxConfigService.getOne(wrapper);
        if (wc == null){
            resMap.put("errorMsg","内部错误，协会配置信息不存在!");
            return resMap;
        }
        //微信授权获取openId
        JSONObject jo= ClientUtils.getH5AccessToken(wc.getAppId(),wc.getAppSecret(), code);
        if (jo == null || StringUtils.isEmpty(jo.getString("openid"))){
            logger.info("获取授权信息失败，错误码："+jo.getIntValue("errcode"));
            resMap.put("errorMsg","获取授权信息失败，错误码："+jo.getIntValue("errcode"));
            return resMap;
        }
        resMap.put("openId",jo.getString("openid"));
        return resMap;
    }

    /**
     * 根据openId和token获取用户信息
     * @param openId openId
     * @param accessToken 接口调用凭据
     * @return JSONObject
     */
    public static JSONObject getUserInfo(String openId,String accessToken){
        //拼接地址
        StringBuffer sbUrl = new StringBuffer("https://api.weixin.qq.com/cgi-bin/user/info?");
        sbUrl.append("access_token=")
                .append(accessToken)
                .append("&openid=")
                .append(openId)
                .append("&lang=zh_CN");
        JSONObject res = null;
        try {
            HttpClient client = HttpClientBuilder.create().build();//构建一个Client
            HttpGet get = new HttpGet(sbUrl.toString());//构建一个GET请求
            HttpResponse response = client.execute(get);//提交GET请求
            HttpEntity result = response.getEntity();//拿到返回的HttpResponse的"实体"
            String r = EntityUtils.toString(result);
            System.out.println(r);//打印返回的信息
            System.out.println("转码后---------------------");
            String str = new String(r.getBytes("ISO-8859-1"),"UTF-8");
            res = JSONObject.parseObject(str);
        }catch (Exception e){
            e.printStackTrace();
            return res;
        }
        return res;
    }

}
